import React, { useEffect, useState } from "react";
import { Button, Table, Spin, Popconfirm, message } from "antd";
import { getList } from "../network/api";
import { Link, useNavigate } from "react-router-dom";
import { deleteArticle } from "../network/api";
import dayjs from "dayjs";
import "./less/list.less";

const { Column, ColumnGroup } = Table;

const List = () => {
  let [isLoading, setLoading] = useState(false);
  let [tableData, setTableData] = useState([]);
  const navigate = useNavigate();
  let [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // 编辑
  const toEditHandle = (id) => {
    navigate("/edit/" + id);
  };
  // 删除
  const handleDelete = async (id) => {
    setLoading(true);
    try {
      const result = await deleteArticle(id);
      if (!result.errCode) {
        message.success("文章删除成功!");
        queryList(pagination.current, pagination.pageSize);
      }
    } catch (error) {
      console.log("error: ", error);
    }
    setLoading(false);
  };
  const columns = [
    {
      title: "文章内容",
      dataIndex: "title",
      key: "title",
      width: "65%",
      render: (text, record) => (
        <div>
          <Link to="/" className="title-link">
            {" "}
            {record.title}
          </Link>
          <p className="sub-title">
            {" "}
            《{record.subTitle}》 {record.author}
          </p>
        </div>
      ),
    },
    {
      title: "更新时间",
      dataIndex: "date",
      key: "date",
      align: "center",
    },
    {
      title: "操作",
      dataIndex: "actions",
      key: "actions",
      align: "center",
      render: (text, record) => (
        <>
          <Button
            type="primary"
            size="small"
            style={{ marginRight: "8px" }}
            onClick={() => toEditHandle(record.id)}
          >
            编辑
          </Button>
          <Popconfirm
            placement="bottom"
            title="确定删除此文章?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];
  useEffect(() => {
    queryList(pagination.current, pagination.pageSize);
  }, []);
  // 获取文章数据
  const queryList = async (num, count) => {
    isLoading = setLoading(true);
    try {
      const result = await getList({ num, count });

      if (result.errCode == 0) {
        let {
          data: { arr: articleList, count, num, total },
        } = result;
        pagination = setPagination({
          current: num,
          total,
        });

        let newData = articleList
          .sort((a, b) => new Date(b.date) - new Date(a.date))
          .map((item) => {
            let formatDate = dayjs(item.date).format("YYYY-MM-DD HH:mm:ss");
            return { ...item, key: item.id, date: formatDate };
          });

        tableData = setTableData(newData);
        message.success(result.message);
      }
    } catch (error) {}
    isLoading = setLoading(false);
  };

  //分页
  const pageChange = (arg) => {
    queryList(arg.current, arg.pageSize);
  };
  return (
    <div className="list-box">
      <Spin spinning={isLoading}>
        <Table
          dataSource={tableData}
          columns={columns}
          pagination={pagination}
          onChange={pageChange}
          size="mini"
        ></Table>
      </Spin>
    </div>
  );
};

export default List;
